# encoding: utf-8
# @File   : http_client.py
# @Author : 乖孩子

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry


class HttpClient:
    def __init__(self, logger, max_retries=3, timeout=10):
        """初始化HTTP客户端"""
        self.logger = logger
        self.session = requests.Session()
        self.max_retries = max_retries
        self.timeout = timeout

        # 配置重试策略
        retry_strategy = Retry(
            total=max_retries,
            backoff_factor=0.5,
            status_forcelist=[429, 500, 502, 503, 504]
        )

        # 应用重试策略到所有HTTP和HTTPS请求
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.session.mount("http://", adapter)
        self.session.mount("https://", adapter)

        self.logger.info(f"HTTP客户端初始化完成 - 最大重试次数: {max_retries}, 超时时间: {timeout}秒")

    def get(self, url, headers=None, params=None):
        """发送GET请求"""
        self.logger.debug(f"发送GET请求: {url}")
        try:
            response = self.session.get(
                url,
                headers=headers,
                params=params,
                timeout=self.timeout
            )
            response.raise_for_status()
            self.logger.debug(f"GET请求成功: {url}")
            return True, response.json()
        except Exception as e:
            error_info = {
                "url": url,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
            self.logger.error(f"GET请求失败: {url}, 错误: {error_info}")
            return False, error_info

    def post(self, url, headers=None, data=None):
        """发送POST请求"""
        self.logger.debug(f"发送POST请求: {url}")
        try:
            response = self.session.post(
                url,
                headers=headers,
                json=data,
                timeout=self.timeout
            )
            response.raise_for_status()
            self.logger.debug(f"POST请求成功: {url}, 状态码: {response.status_code}")
            return True, {
                "status_code": response.status_code,
                "data": response.json()
            }
        except Exception as e:
            # 获取更详细的错误信息
            error_info = {
                "url": url,
                "error_type": type(e).__name__,
                "error_message": str(e)
            }

            # 尝试获取状态码（如果有）
            if hasattr(e, 'response') and e.response is not None:
                error_info["status_code"] = e.response.status_code

            self.logger.error(f"POST请求失败: {url}, 错误: {error_info}")
            return False, error_info